package com.kvest.sqlitetest.adapter;

import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.View;

public class DynamicCursorAdapter extends SimpleCursorAdapter {
    private static final int MIN_DIFFERENCE = 5;

    private LoadMoreListener loadMoreListener;

    public DynamicCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to,
                                LoadMoreListener loadMoreListener) {
        super(context, layout, c, from, to);
        this.loadMoreListener = loadMoreListener;

        if (c != null && c.getCount() == 0 && loadMoreListener != null) {
            loadMoreListener.loadMore();
        }
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        super.bindView(view, context, cursor);

        if (cursor.getCount() - cursor.getPosition() <= MIN_DIFFERENCE) {
            loadMore();
        }
    }

    private void loadMore() {
        if (loadMoreListener != null) {
            loadMoreListener.loadMore();
        }
    }

    public interface LoadMoreListener {
        public void loadMore();
    }
}
